How to useHTML | DOM Anchor Object in ReactJS
This approach use HTML DOM Anchor element to link a file adderess along with the anchor tag and download file using link.download with custom file name.
Example: Here link the anchor tag to the pdf address / URL and use link.download to to save the file in local storage.
Javascript
import React from "react" ; const App = () => { const onButtonClick = () => { const pdfUrl = "Sample.pdf" ; const link = document.createElement( "a" ); link.href = pdfUrl; link.download = "document.pdf" ; // specify the filename document.body.appendChild(link); link.click(); document.body.removeChild(link); }; return ( <> <center> <h1>Welcome to Geeks for Geeks</h1> <h3> Click on below button to download PDF file </h3> <button onClick={onButtonClick}> Download PDF </button> </center> </> ); }; export default App; |
Steps to run the program: To run the application using the below command:
npm start
Output: The output will be visible in http://localhost:3000/
How to download PDF file in ReactJS ?
To download pdf in React JS there are methods given in JavaScript and HTML DOM. They provide a convenient way to download files and store them in local computers. Here we will use locally stored pdf files in the project folder to use as a sample pdf downloaded by the browser.
These are the approaches to download a PDF in React JS projects.
Table of Content
- Using HTML | DOM Anchor Object
- Using fetch() method
Steps to create the application:
Step 1: Create a React.js application using the following command:
npx create-react-app <project-name>
Step 2: After creating your project folder, move into that directory using the following command:
cd <project-name>
Step 3: You need to copy and paste your PDF file into the Public folder.
Project Structure: Your project structure will look like this:
Let’s understand the implementation through example.